package com.y2w.uikit.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;

import com.example.maa2.uikit.R;
import com.y2w.uikit.common.AttachmentStore;
import com.y2w.uikit.common.BitmapDecoder;
import com.y2w.uikit.common.StorageType;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * 图片操作工具包
 * 
 * @author on man
 * @version 1.0
 * @created 2012-3-21
 */
public class ImageUtils {
	public static class ImageSize {
		public int width = 0;
		public int height = 0;

		public ImageSize(int width, int height) {
			this.width = width;
			this.height = height;
		}
	}
	public final static float MAX_IMAGE_RATIO = 5f;
	public static Bitmap getDefaultBitmapWhenGetFail() {
		try {
			return getBitmapImmutableCopy(NimUIKit.getContext().getResources(), R.drawable.nim_image_download_failed);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static final Bitmap getBitmapImmutableCopy(Resources res, int id) {
		return getBitmap(res.getDrawable(id)).copy(Bitmap.Config.RGB_565, false);
	}

	public static final Bitmap getBitmap(Drawable dr) {
		if (dr == null) {
			return null;
		}

		if (dr instanceof BitmapDrawable) {
			return ((BitmapDrawable) dr).getBitmap();
		}

		return null;
	}
	public static Bitmap rotateBitmapInNeeded(String path, Bitmap srcBitmap) {
		if (TextUtils.isEmpty(path) || srcBitmap == null) {
			return null;
		}

		ExifInterface localExifInterface;
		try {
			localExifInterface = new ExifInterface(path);
			int rotateInt = localExifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			float rotate = getImageRotate(rotateInt);
			if (rotate != 0) {
				Matrix matrix = new Matrix();
				matrix.postRotate(rotate);
				Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
						srcBitmap.getWidth(), srcBitmap.getHeight(), matrix,
						false);
				if (dstBitmap == null) {
					return srcBitmap;
				} else {
					if (srcBitmap != null && !srcBitmap.isRecycled()) {
						srcBitmap.recycle();
					}
					return dstBitmap;
				}
			} else {
				return srcBitmap;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return srcBitmap;
		}
	}
	/**
	 * 写图片文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
	 * 
	 * @throws IOException
	 */
	public static void saveImage(Context context, String fileName, Bitmap bitmap)
			throws IOException {
		saveImage(context, fileName, bitmap, 100);
	}

	public static void saveImage(Context context, String fileName,
			Bitmap bitmap, int quality) throws IOException {
		if (bitmap == null || fileName == null || context == null)
			return;

		FileOutputStream fos = context.openFileOutput(fileName,
				Context.MODE_PRIVATE);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, quality, stream);
		byte[] bytes = stream.toByteArray();
		fos.write(bytes);
		fos.close();
	}

	/**
	 * 写图片文件到SD卡
	 * 
	 * @throws IOException
	 */
	public static void saveImageToSD(Context ctx, String filePath,
			Bitmap bitmap, int quality) throws IOException {
		if (bitmap != null) {
			File file = new File(filePath.substring(0,
					filePath.lastIndexOf(File.separator)));
			if (!file.exists()) {
				file.mkdirs();
			}
			file = new File(filePath);
			if(!file.exists()){
				file.createNewFile();
			}
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(filePath));
			bitmap.compress(CompressFormat.JPEG, quality, bos);
			bos.flush();
			bos.close();
			if (ctx != null) {
				scanPhoto(ctx, filePath);
			}
		}
	}

	/**
	 * 消息图片最长边长为960像素
	 */
	private static final int SEND_BITMAP_MAX_SIDE = 1920;




	/**
	 * 发送消息是压缩图片
	 * @param filePath
	 * @param bitmap
	 */
	public static void saveImageForSendMeg(String filePath,
			Bitmap bitmap,Context context) throws IOException{
		if (bitmap != null) {
	            int bitmapWidth = bitmap.getWidth();
	            int bitmapHeight = bitmap.getHeight();
	            // 缩放图片的尺寸
	            float scale = 1;
	            if(bitmapWidth > SEND_BITMAP_MAX_SIDE || bitmapHeight > SEND_BITMAP_MAX_SIDE){
	            	if(bitmapWidth > bitmapHeight){
	            		scale =  (float)SEND_BITMAP_MAX_SIDE / bitmapWidth;
	            	}else{
	            		scale =  (float)SEND_BITMAP_MAX_SIDE / bitmapHeight;
	            	}
	            }
	            Matrix matrix = new Matrix();
	            matrix.postScale(scale, scale);
	            // 产生缩放后的Bitmap对象
	            Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);

	            // save file
	            File myCaptureFile = new File(filePath);
	            FileOutputStream out = new FileOutputStream(myCaptureFile);
	            if(resizeBitmap.compress(CompressFormat.JPEG, 80, out)){
	                out.flush();
	                out.close();
	            }
	            if(!bitmap.isRecycled()){
	                bitmap.recycle();//记得释放资源，否则会内存溢出
	            }
	            if(!resizeBitmap.isRecycled()){
	                resizeBitmap.recycle();
	            }

			scanPhoto(context, filePath);
		}
	}

	public static void saveBackgroundImage(Context ctx, String filePath,
			Bitmap bitmap, int quality) throws IOException {
		if (bitmap != null) {
			File file = new File(filePath.substring(0,
					filePath.lastIndexOf(File.separator)));
			if (!file.exists()) {
				file.mkdirs();
			}
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(filePath));
			bitmap.compress(CompressFormat.PNG, quality, bos);
			bos.flush();
			bos.close();
			if (ctx != null) {
				scanPhoto(ctx, filePath);
			}
		}
	}

	/**
	 * 获取缩略图
	 * @param path
	 * @param maxLength
	 * @return
	 */
	public static Bitmap getImageThumbnail(String path, int maxLength) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);
		int realWidth = options.outWidth;
		int realHeight = options.outHeight;
		//需要缩放
		if(Math.max(realWidth, realHeight) > maxLength){
			if(realWidth > realHeight){
				int h = realHeight * maxLength / realWidth;
				realHeight = h > maxLength ? maxLength : h;
				realWidth = 400;
			}
			else{
				int w = realWidth * maxLength / realHeight;
				realWidth = w > 400 ? 400 : w;
				realHeight = maxLength;
			}
		}

		options.inJustDecodeBounds = false;
		options.inDither = false;
		options.inPreferredConfig = Bitmap.Config.RGB_565;
		options.outWidth = realWidth;
		options.outHeight = realHeight;
		try{
			bitmap = BitmapFactory.decodeFile(path, options);
			return ThumbnailUtils.extractThumbnail(bitmap, realWidth, realHeight);
		}
		catch(OutOfMemoryError e){
		}
		return null;
	}

	/**
	 * 让Gallery上能马上看到该图片
	 */
	private static void scanPhoto(Context ctx, String imgFileName) {
		Intent mediaScanIntent = new Intent(
				Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File file = new File(imgFileName);
		Uri contentUri = Uri.fromFile(file);
		mediaScanIntent.setData(contentUri);
		ctx.sendBroadcast(mediaScanIntent);
	}

	/**
	 * 获取bitmap
	 *
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static Bitmap getBitmap(Context context, String fileName) {
		FileInputStream fis = null;
		Bitmap bitmap = null;
		try {
			fis = context.openFileInput(fileName);
			bitmap = BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
		} catch (OutOfMemoryError e) {
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return bitmap;
	}

	/**
	 * 获取bitmap
	 *
	 * @param filePath
	 * @return
	 */
	public static Bitmap getBitmapByPath(String filePath) {
		return getBitmapByPath(filePath, null);
	}

	public static Bitmap getBitmapByPath(String filePath,
			BitmapFactory.Options opts) {
		FileInputStream fis = null;
		Bitmap bitmap = null;
		try {
			File file = new File(filePath);
			fis = new FileInputStream(file);
			bitmap = BitmapFactory.decodeStream(fis, null, opts);
		} catch (FileNotFoundException e) {
		} catch (OutOfMemoryError e) {
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return bitmap;
	}

	/**
	 * 获取bitmap
	 *
	 * @param file
	 * @return
	 */
	public static Bitmap getBitmapByFile(File file) {
		FileInputStream fis = null;
		Bitmap bitmap = null;
		try {
			fis = new FileInputStream(file);
			bitmap = BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
		} catch (OutOfMemoryError e) {
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return bitmap;
	}

	/**
	 * 使用当前时间戳拼接一个唯一的文件名
	 * @return
	 */
	public static String getTempFileName() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
		String fileName = format.format(new Timestamp(System
				.currentTimeMillis()));
		return fileName;
	}

	/**
	 * 获取照相机使用的目录
	 *
	 * @return
	 */
	public static String getCamerPath() {
		return Environment.getExternalStorageDirectory() + File.separator
				+ "FounderNews" + File.separator;
	}



	/**
	 * 通过uri获取文件的绝对路径
	 *
	 * @param uri
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String getAbsoluteImagePath(Activity context, Uri uri) {
		String imagePath = "";
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.managedQuery(uri, proj, // Which columns to
														// return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)

		if (cursor != null) {
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			if (cursor.getCount() > 0 && cursor.moveToFirst()) {
				imagePath = cursor.getString(column_index);
			}
		}

		return imagePath;
	}

	/**
	 * 获取SD卡中最新图片路径
	 *
	 * @return
	 */
	public static String getLatestImage(Activity context) {
		String latestImage = null;
		String[] items = { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATA };
		Cursor cursor = context.managedQuery(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null,
				null, MediaStore.Images.Media._ID + " desc");

		if (cursor != null && cursor.getCount() > 0) {
			cursor.moveToFirst();
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
					.moveToNext()) {
				latestImage = cursor.getString(1);
				break;
			}
		}

		return latestImage;
	}

	/**
	 * 计算缩放图片的宽高
	 *
	 * @param img_size
	 * @param square_size
	 * @return
	 */
	public static int[] scaleImageSize(int[] img_size, int square_size) {
		if (img_size[0] <= square_size && img_size[1] <= square_size)
			return img_size;
		double ratio = square_size
				/ (double) Math.max(img_size[0], img_size[1]);
		return new int[] { (int) (img_size[0] * ratio),
				(int) (img_size[1] * ratio) };
	}

	/**
	 * 创建缩略图
	 *
	 * @param context
	 * @param largeImagePath
	 *            原始大图路径
	 * @param thumbfilePath
	 *            输出缩略图路径
	 * @param square_size
	 *            输出图片宽度
	 * @param quality
	 *            输出图片质量
	 * @throws IOException
	 */
	public static void createImageThumbnail(Context context,
			String largeImagePath, String thumbfilePath, int square_size,
			int quality) throws IOException {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inSampleSize = 1;
		// 原始图片bitmap
		Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);

		if (cur_bitmap == null)
			return;

		// 原始图片的高宽
		int[] cur_img_size = new int[] { cur_bitmap.getWidth(),
				cur_bitmap.getHeight() };
		// 计算原始图片缩放后的宽高
		int[] new_img_size = scaleImageSize(cur_img_size, square_size);
		// 生成缩放后的bitmap
		Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0],
				new_img_size[1]);
		// 生成缩放后的图片文件
		saveImageToSD(null, thumbfilePath, thb_bitmap, quality);
	}

	/**
	 * 放大缩小图片
	 *
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		Bitmap newbmp = null;
		if (bitmap != null) {
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();
			Matrix matrix = new Matrix();
			float scaleWidht = ((float) w / width);
			float scaleHeight = ((float) h / height);
			matrix.postScale(scaleWidht, scaleHeight);
			try {
				newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
						matrix, true);
			} catch (Exception e) {
				newbmp = bitmap;
			}
		}
		return newbmp;
	}

	/**
	 * 按原比例缩放图片
	 *
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap zoomScaleBitmap(Bitmap bitmap, int w, int h) {
		if (bitmap == null) {
			return null;
		}
		// 获取这个图片的宽和高
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int newWidth = w;
		int newHeight = h;
		// 定义预转换成的图片的宽度和高度
		if (width * h > height * w) {
			newHeight = height * w / width;
		} else {
			newWidth = width * h / height;
		}
		// 计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		// 旋转图片 动作
		// matrix.postRotate(45);
		// 创建新的图片
		Bitmap resizedBitmap = null;
		try {
			resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
					matrix, true);
		} catch (Exception e) {
			resizedBitmap = bitmap;
		}
		return resizedBitmap;
	}

	public static Bitmap scaleBitmap(Bitmap bitmap) {
		// 获取这个图片的宽和高
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		// 定义预转换成的图片的宽度和高度
		int newWidth = 200;
		int newHeight = 200;
		// 计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		// 旋转图片 动作
		// matrix.postRotate(45);
		// 创建新的图片
		Bitmap resizedBitmap = null;
		try {
			resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
					matrix, true);
		} catch (Exception e) {
			resizedBitmap = bitmap;
		}
		return resizedBitmap;
	}

	/**
	 * (缩放)重绘图片
	 *
	 * @param context
	 *            Activity
	 * @param bitmap
	 * @return
	 */
	public static Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
		DisplayMetrics dm = new DisplayMetrics();
		context.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int rHeight = dm.heightPixels;
		int rWidth = dm.widthPixels;
		// float rHeight=dm.heightPixels/dm.density+0.5f;
		// float rWidth=dm.widthPixels/dm.density+0.5f;
		// int height=bitmap.getScaledHeight(dm);
		// int width = bitmap.getScaledWidth(dm);
		int height = bitmap.getHeight();
		int width = bitmap.getWidth();
		float zoomScale;
		/** 方式1 **/
		// if(rWidth/rHeight>width/height){//以高为准
		// zoomScale=((float) rHeight) / height;
		// }else{
		// //if(rWidth/rHeight<width/height)//以宽为准
		// zoomScale=((float) rWidth) / width;
		// }
		/** 方式2 **/
		// if(width*1.5 >= height) {//以宽为准
		// if(width >= rWidth)
		// zoomScale = ((float) rWidth) / width;
		// else
		// zoomScale = 1.0f;
		// }else {//以高为准
		// if(height >= rHeight)
		// zoomScale = ((float) rHeight) / height;
		// else
		// zoomScale = 1.0f;
		// }
		/** 方式3 **/
		if (width >= rWidth)
			zoomScale = ((float) rWidth) / width;
		else
			zoomScale = 1.0f;
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 缩放图片动作
		matrix.postScale(zoomScale, zoomScale);
		Bitmap resizedBitmap = null;
		try {
			resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
					bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		} catch (Exception e) {
			resizedBitmap = bitmap;
		}
		return resizedBitmap;
	}

	/**
	 * 将Drawable转化为Bitmap
	 *
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
				.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
				: Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);
		return bitmap;

	}

	/**
	 * 获得圆角图片的方法
	 *
	 * @param bitmap
	 * @param roundPx
	 *            一般设成14
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	/**
	 * 获得带倒影的图片方法
	 *
	 * @param bitmap
	 * @return
	 */
	public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
		final int reflectionGap = 4;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
				width, height / 2, matrix, false);

		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);

		Canvas canvas = new Canvas(bitmapWithReflection);
		canvas.drawBitmap(bitmap, 0, 0, null);
		Paint deafalutPaint = new Paint();
		canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);

		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
				bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
				0x00ffffff, TileMode.CLAMP);
		paint.setShader(shader);
		// Set the Transfer mode to be porter duff and destination in
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// Draw a rectangle using the paint with our linear gradient
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);

		return bitmapWithReflection;
	}

	/**
	 * 将bitmap转化为drawable
	 *
	 * @param bitmap
	 * @return
	 */
	public static Drawable bitmapToDrawable(Bitmap bitmap) {
		Drawable drawable = new BitmapDrawable(bitmap);
		return drawable;
	}

	/**
	 * 获取图片类型
	 *
	 * @param file
	 * @return
	 */
	public static String getImageType(File file) {
		if (file == null || !file.exists()) {
			return null;
		}
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			String type = getImageType(in);
			return type;
		} catch (IOException e) {
			return null;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 获取图片的类型信息
	 *
	 * @param in
	 * @return
	 * @see #getImageType(byte[])
	 */
	public static String getImageType(InputStream in) {
		if (in == null) {
			return null;
		}
		try {
			byte[] bytes = new byte[8];
			in.read(bytes);
			return getImageType(bytes);
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * 获取图片的类型信息
	 *
	 * @param bytes
	 *            2~8 byte at beginning of the image file
	 * @return image mimetype or null if the file is not image
	 */
	public static String getImageType(byte[] bytes) {
		if (isJPEG(bytes)) {
			return "image/jpeg";
		}
		if (isGIF(bytes)) {
			return "image/gif";
		}
		if (isPNG(bytes)) {
			return "image/png";
		}
		if (isBMP(bytes)) {
			return "application/x-bmp";
		}
		return null;
	}

	private static boolean isJPEG(byte[] b) {
		if (b.length < 2) {
			return false;
		}
		return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
	}

	private static boolean isGIF(byte[] b) {
		if (b.length < 6) {
			return false;
		}
		return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8'
				&& (b[4] == '7' || b[4] == '9') && b[5] == 'a';
	}

	private static boolean isPNG(byte[] b) {
		if (b.length < 8) {
			return false;
		}
		return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78
				&& b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10
				&& b[6] == (byte) 26 && b[7] == (byte) 10);
	}

	private static boolean isBMP(byte[] b) {
		if (b.length < 2) {
			return false;
		}
		return (b[0] == 0x42) && (b[1] == 0x4d);
	}
	public static float getImageRotate(int rotate) {
		float f;
		if (rotate == 6) {
			f = 90.0F;
		} else if (rotate == 3) {
			f = 180.0F;
		} else if (rotate == 8) {
			f = 270.0F;
		} else {
			f = 0.0F;
		}

		return f;
	}

	public static String makeThumbnail(Context context, File imageFile) {
		String thumbFilePath = StorageUtil.getWritePath(imageFile.getName(),
				StorageType.TYPE_THUMB_IMAGE);
		File thumbFile = AttachmentStore.create(thumbFilePath);
		if (thumbFile == null) {
			return null;
		}

		//TODO
       /* boolean result = scaleThumbnail(
                imageFile,
                thumbFile,
                MsgViewHolderThumbBase.getImageMaxEdge(),
                MsgViewHolderThumbBase.getImageMinEdge(),
                Bitmap.CompressFormat.JPEG,
                60);
        if (!result) {
            AttachmentStore.delete(thumbFilePath);
            return null;
        }
*/
		return thumbFilePath;
	}

	public static Boolean scaleThumbnail(File srcFile, File dstFile, int dstMaxWH, int dstMinWH, Bitmap.CompressFormat compressFormat, int quality) {
		Boolean bRet = false;
		Bitmap srcBitmap = null;
		Bitmap dstBitmap = null;
		BufferedOutputStream bos = null;

		try {
			int[] bound = BitmapDecoder.decodeBound(srcFile);
			ImageSize size = getThumbnailDisplaySize(bound[0], bound[1], dstMaxWH, dstMinWH);
			srcBitmap = BitmapDecoder.decodeSampled(srcFile.getPath(), size.width, size.height);

			// ��ת
			ExifInterface localExifInterface = new ExifInterface(srcFile.getAbsolutePath());
			int rotateInt = localExifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			float rotate = getImageRotate(rotateInt);

			Matrix matrix = new Matrix();
			matrix.postRotate(rotate);

			float inSampleSize = 1;

			if (srcBitmap.getWidth() >= dstMinWH && srcBitmap.getHeight() <= dstMaxWH
					&& srcBitmap.getWidth() >= dstMinWH && srcBitmap.getHeight() <= dstMaxWH) {
				//����һ���õ���srcBitmap�ߴ綼���Ҫ�󣬲���Ҫ��������
			} else {
				if (srcBitmap.getWidth() != size.width || srcBitmap.getHeight() != size.height) {
					float widthScale = (float) size.width / (float) srcBitmap.getWidth();
					float heightScale = (float) size.height / (float) srcBitmap.getHeight();

					if (widthScale >= heightScale) {
						size.width = srcBitmap.getWidth();
						size.height /= widthScale;//�ض�С��srcBitmap.getHeight()
						inSampleSize = widthScale;
					} else {
						size.width /= heightScale;//�ض�С��srcBitmap.getWidth()
						size.height = srcBitmap.getHeight();
						inSampleSize = heightScale;
					}
				}
			}

			matrix.postScale(inSampleSize, inSampleSize);

			if (rotate == 0 && inSampleSize == 1) {
				dstBitmap = srcBitmap;
			} else {
				dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, size.width, size.height, matrix, true);
			}

			bos = new BufferedOutputStream(new FileOutputStream(dstFile));
			dstBitmap.compress(compressFormat, quality, bos);
			bos.flush();
			bRet = true;
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (srcBitmap != null && !srcBitmap.isRecycled()) {
				srcBitmap.recycle();
				srcBitmap = null;
			}

			if (dstBitmap != null && !dstBitmap.isRecycled()) {
				dstBitmap.recycle();
				dstBitmap = null;
			}
		}
		return bRet;
	}

	public static ImageSize getThumbnailDisplaySize(float srcWidth, float srcHeight, float dstMaxWH, float dstMinWH) {
		if (srcWidth <= 0 || srcHeight <= 0) { // bounds check
			return new ImageSize((int)dstMinWH, (int)dstMinWH);
		}

		float shorter;
		float longer;
		boolean widthIsShorter;

		//store
		if (srcHeight < srcWidth) {
			shorter = srcHeight;
			longer = srcWidth;
			widthIsShorter = false;
		} else {
			shorter = srcWidth;
			longer = srcHeight;
			widthIsShorter = true;
		}

		if (shorter < dstMinWH) {
			float scale = dstMinWH / shorter;
			shorter = dstMinWH;
			if (longer * scale > dstMaxWH) {
				longer = dstMaxWH;
			} else {
				longer *= scale;
			}
		}
		else if (longer > dstMaxWH) {
			float scale = dstMaxWH / longer;
			longer = dstMaxWH;
			if (shorter * scale < dstMinWH) {
				shorter = dstMinWH;
			} else {
				shorter *= scale;
			}
		}

		//restore
		if (widthIsShorter) {
			srcWidth = shorter;
			srcHeight = longer;
		} else {
			srcWidth = longer;
			srcHeight = shorter;
		}

		return new ImageSize((int) srcWidth, (int) srcHeight);
	}

	public static File getScaledImageFileWithMD5(File imageFile, String mimeType) {
		String filePath = imageFile.getPath();

		if (!isInvalidPictureFile(mimeType)) {
			// LogUtil.i("ImageUtil", "is invalid picture file");
			return null;
		}

		String tempFilePath = getTempFilePath(FileUtil.getExtensionName(filePath));
		File tempImageFile = AttachmentStore.create(tempFilePath);
		if (tempImageFile == null) {
			return null;
		}

		Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
		int maxWidth = 720;
		int quality = 60;

		if (scaleImage(imageFile, tempImageFile, maxWidth, compressFormat, quality)) {
			return tempImageFile;
		} else {
			return null;
		}
	}

	private static String getTempFilePath(String extension) {
		return StorageUtil.getWritePath(
				NimUIKit.getContext(),
				"temp_image_" + UUID.randomUUID() + "." + extension,
				StorageType.TYPE_TEMP);
	}

	public static Boolean scaleImage(File srcFile, File dstFile, int dstMaxWH, Bitmap.CompressFormat compressFormat, int quality) {
		Boolean success = false;

		try {
			int inSampleSize = SampleSizeUtil.calculateSampleSize(srcFile.getAbsolutePath(), dstMaxWH * dstMaxWH);
			Bitmap srcBitmap = BitmapDecoder.decodeSampled(srcFile.getPath(), inSampleSize);
			if (srcBitmap == null) {
				return success;
			}

			// ��ת
			ExifInterface localExifInterface = new ExifInterface(srcFile.getAbsolutePath());
			int rotateInt = localExifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			float rotate = getImageRotate(rotateInt);

			Bitmap dstBitmap;
			float scale = (float) Math.sqrt(((float) dstMaxWH * (float) dstMaxWH) / ((float) srcBitmap.getWidth() * (float) srcBitmap.getHeight()));
			if (rotate == 0f && scale >= 1) {
				dstBitmap = srcBitmap;
			} else {
				try {
					Matrix matrix = new Matrix();
					if (rotate != 0) {
						matrix.postRotate(rotate);
					}
					if (scale < 1) {
						matrix.postScale(scale, scale);
					}
					dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
				} catch (OutOfMemoryError e) {
					BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile));
					srcBitmap.compress(compressFormat, quality, bos);
					bos.flush();
					bos.close();
					success = true;

					if (!srcBitmap.isRecycled())
						srcBitmap.recycle();
					srcBitmap = null;

					return success;
				}
			}

			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile));
			dstBitmap.compress(compressFormat, quality, bos);
			bos.flush();
			bos.close();
			success = true;

			if (!srcBitmap.isRecycled())
				srcBitmap.recycle();
			srcBitmap = null;

			if (!dstBitmap.isRecycled())
				dstBitmap.recycle();
			dstBitmap = null;
		} catch (Exception e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		return success;
	}

	public static ImageSize getThumbnailDisplaySize(int maxSide, int minSide, String imagePath) {
		int[] bound = BitmapDecoder.decodeBound(imagePath);
		ImageSize imageSize = getThumbnailDisplaySize(bound[0], bound[1], maxSide, minSide);
		return imageSize;
	}

	public static int[] getBoundWithLength(int maxSide, Object imageObject, boolean resizeToDefault) {
		int width = -1;
		int height = -1;

		int[] bound;
		if (String.class.isInstance(imageObject)) {
			bound = BitmapDecoder.decodeBound((String) imageObject);
			width = bound[0];
			height = bound[1];
		} else if (Integer.class.isInstance(imageObject)) {
			bound = BitmapDecoder.decodeBound(NimUIKit.getContext().getResources(), (Integer) imageObject);
			width = bound[0];
			height = bound[1];
		} else if (InputStream.class.isInstance(imageObject)) {
			bound = BitmapDecoder.decodeBound((InputStream) imageObject);
			width = bound[0];
			height = bound[1];
		}

		int defaultWidth = maxSide;
		int defaultHeight = maxSide;
		if (width <= 0 || height <= 0) {
			width = defaultWidth;
			height = defaultHeight;
		} else if (resizeToDefault) {
			if (width > height) {
				height = (int) (defaultWidth * ((float) height / (float) width));
				width = defaultWidth;
			} else {
				width = (int) (defaultHeight * ((float) width / (float) height));
				height = defaultHeight;
			}
		}

		return new int[] {width, height};
	}

	/**
	 *
	 *
	 * @return
	 */
	public static Bitmap getBitmapFromDrawableRes(int res) {
		try {
			return getBitmapImmutableCopy(NimUIKit.getContext().getResources(), res);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isInvalidPictureFile(String mimeType) {
		String lowerCaseFilepath = mimeType.toLowerCase();
		return (lowerCaseFilepath.contains("jpg") || lowerCaseFilepath.contains("jpeg")
				|| lowerCaseFilepath.toLowerCase().contains("png") || lowerCaseFilepath.toLowerCase().contains("bmp") || lowerCaseFilepath
				.toLowerCase().contains("gif"));
	}

	/**
	 * 获取视频缩略图
	 * @param path
	 * @param maxLength
	 * @return
	 */

	public static Bitmap getVideoThumbnail(String path, int maxLength) {
		Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
		if(bitmap == null){
			return null;
		}
		int realWidth = bitmap.getWidth();
		int realHeight = bitmap.getHeight();
		//需要缩放
		if(Math.max(realWidth, realHeight) > maxLength){
			if(realWidth > realHeight){
				realHeight = realHeight * maxLength / realWidth;
				realWidth = maxLength;
			}
			else{
				realWidth = realWidth * maxLength / realHeight;
				realHeight = maxLength;
			}
		}

		try{
			return ThumbnailUtils.extractThumbnail(bitmap, realWidth, realHeight);
		}
		catch(OutOfMemoryError e){
		}
		return null;
	}




}
